from motor.motor_asyncio import AsyncIOMotorDatabase
from models.reviews import Review
from .base import BaseRepository

class ReviewRepository(BaseRepository[Review]):
    def __init__(self, db: AsyncIOMotorDatabase):
        super().__init__("reviews", db)

    async def get_by_rb_id(self, rb_id: str) -> Review:
        """
        获取数据
        """
        return await self.collection.find_one({"rbId": rb_id})

    async def create_or_update(self, review: Review) -> Review:
        """
        插入或更新数据
        """
        query = {"rbId": review.rbId}
        review_dict = review.model_dump()
        
        # 使用 update_one 方法，upsert=True 表示如果不存在则插入，存在则更新
        await self.collection.update_one(
            query,
            {
                "$set": review_dict
            },
            upsert=True
        )
        
        # 返回更新后的文档
        return await self.get_by_rb_id(review.rbId)    